package post

import (
	"center-platform/internal/controller/response"
	"center-platform/internal/controller/v1/post/entity"
	"center-platform/internal/controller/v1/post/service"
	"github.com/gin-gonic/gin"
	"reflect"
	"strconv"
)

func Info(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			response.ApiError(c, "服务器错误")
			return
		}
	}()
	var postSer service.PostImpl = new(service.PostService)
	id, _ := c.GetQuery("id")
	postId, _ := strconv.Atoi(id)
	err, post := postSer.Info(postId)
	if err != nil {
		response.ApiError(c, err.Error())
		return
	}
	response.ApiSuccess(c, post)
}

func List(c *gin.Context) {
	var postSer service.PostImpl = new(service.PostService)
	var searchParam entity.SearchParam
	err := c.ShouldBindJSON(&searchParam)
	if err != nil {
		response.ApiError(c, err.Error())
		return
	}
	//if len(searchParam.Ids) < 1 {
	//	param, _ := c.Get("user")
	//	searchParam.Ids = []int{int(reflect.ValueOf(param).FieldByName("UserId").Int())}
	//}
	err, list := postSer.List(&searchParam)
	if err != nil {
		response.ApiError(c, err.Error())
		return
	}
	response.ApiSuccess(c, list)
}

func Add(c *gin.Context) {
	var postSer service.PostImpl = new(service.PostService)
	var post entity.Post
	err := c.ShouldBindJSON(&post)
	if err != nil {
		response.ApiError(c, err.Error())
		return
	}
	param, _ := c.Get("user")
	post.UserID = int(reflect.ValueOf(param).FieldByName("UserId").Int())
	err = postSer.Add(&post)
	if err != nil {
		response.ApiError(c, err.Error())
		return
	}
	response.ApiSuccess(c, "添加成功")
}
